// pages/goods/goodslist/goodslist.js
const app = new getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    prompt: '',
    Base: '', //库路径
    defaultImg: {},
    goods_list: {}, //商品列表
    search_text: '', //搜索内容
    sBuy: 0,
    animation: '',
    goods_info: {}, //商品详情
    spec_list: {}, //规格列表
    attr_value_items_format: '', //选中规格组
    sku_id: 0, //选中规格
    sku_info: {}, //选中规格信息
    stock: 0, //选中规格库存
    promote_price: 0.00, //选中规格价格
    goodsNum: 1, //购买数量,
    data_array: {}, //参数数组
    url: '', //请求地址
    next_page: 1, //下一页,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let siteBaseUrl = getApp().globalData.siteBaseUrl;
    let defaultImg = app.globalData.defaultImg;
    let data_array = {};
    let flag = options.flag;
    let search_text = that.data.search_text;
    let url = '';
    if (flag == 1){
      search_text = options.search_text;
      if (search_text != undefined) {
        data_array = { search_name: search_text }
      }
      url = 'api.php?s=goods/goodsSearchList';
    }else{
      let category_id = options.id;
      if (category_id != undefined) {
        data_array = { category_id: category_id }
      }
      url = 'api.php?s=goods/goodsList';
    }

    app.sendRequest({
      url: url,
      data: data_array,
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data.data != undefined){
          let data = res.data.data;
          let next_page = that.data.next_page+1 ;
          
          that.setData({
            goods_list: data,
            Base: siteBaseUrl,
            defaultImg: defaultImg,
            search_text: search_text,
            next_page: next_page,
            data_array: data_array,
            url: url
          })
          console.log(data);
        }
      },
    })
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this;

    let url = that.data.url;
    let data_array = that.data.data_array;
    let page = that.data.next_page;
    data_array.page = page;

    app.sendRequest({
      url: url,
      data: data_array,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data.data != undefined && res.data.data.length > 0){
          page++;

          let goods_list = that.data.goods_list;
          let new_goods_list = res.data.data;
          let index = goods_list.length;

          for (let key in new_goods_list){
            goods_list[index] = new_goods_list[key];
            index++;
          }

          that.setData({
            next_page: page,
            goods_list: goods_list
          })
        }
      }
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  /**
   * 图片加载失败
   */
  errorImg: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let goods_list = that.data.goods_list;
    let defaultImg = that.data.defaultImg;
    let parm = {};

    if (defaultImg.is_use == 1) {
      let parm_key = "goods_list[" + index + "].pic_cover_small";
      parm[parm_key] = defaultImg.value.default_goods_img;
      that.setData(parm);
    }
  },
  
  /**
   * 页面跳转
   */
  listClick: function(event) {
    var url = event.currentTarget.dataset.url;
    wx.navigateTo({
      url: '/pages'+url,
    })
  },

  /**
   * 输入框绑定事件
   */
  searchInput: function (event) {
    var search_text = event.detail.value;
    this.setData({
      search_text: search_text
    })
  },

  /**
   * 搜索商品
   */
  search: function(event){
    let that = this;
    let search_text = that.data.search_text;
    let data_array = { search_name: search_text };

    app.sendRequest({
      url: 'api.php?s=goods/goodsSearchList',
      data: { search_name: search_text },
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data.data != undefined){
          let data = res.data.data;
          that.setData({
            goods_list: data,
            data_array: data_array,
            url: 'api.php?s=goods/goodsSearchList'
          })
        }
      },
    })
  },

  /**
  * 购物车弹框(动画效果未实现)
  */
  sBuyShow: function (event) {
    let that = this;
    let goods_id = event.currentTarget.dataset.id;
    let attr_value_items_format = '';
    let promote_price = 0.00;

    app.sendRequest({
      url: 'api.php?s=goods/goodsDetail',
      data: {
        goods_id: goods_id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: "POST",
      success: function (res) {
        let code = res.code;
        if (code == 0) {
          let data = res.data;
          that.setData({
            goods_info: data,
          });
          let sku_info = that.data.sku_info;//选中规格信息
          let sku_id = that.data.sku_id; //选中规格
          let attr_value_items = {}; //规格组
          let stock = 0; //库存
          //规格默认选中
          for (let i = 0; i < data.spec_list.length; i++) {
            for (let l = 0; l < data.spec_list[i].value.length; l++) {
              if (l == 0) {
                data.spec_list[i].value[l]['status'] = 1;
                attr_value_items[i] = data.spec_list[i].value[l].spec_id + ':' + data.spec_list[i].value[l].spec_value_id;
                attr_value_items.length = i + 1;
              } else {
                data.spec_list[i].value[l]['status'] = 0;
              }
            }
          }

          //规格组、库存判断
          for (let i = 0; i < data.sku_list.length; i++) {
            let count = 1;
            for (let l = 0; l < attr_value_items.length; l++) {
              if (data.sku_list[i].attr_value_items.indexOf(attr_value_items[l]) == -1) {
                count = 0;
              }
            }
            if (count == 1) {
              attr_value_items_format = data.sku_list[i].attr_value_items_format;
              sku_id = data.sku_list[i].sku_id;
              promote_price = data.sku_list[i].promote_price;
              stock = data.sku_list[i].stock;
              sku_info = data.sku_list[i];
            }
          }

          that.setData({
            spec_list: data.spec_list,
            sku_id: sku_id,
            attr_value_items_format: attr_value_items_format,
            promote_price: promote_price,
            stock: stock
          })

          let animation = wx.createAnimation({
            duration: 3000,
            timingFunction: 'ease-in',
            transformOrigin: "50% 50% 0",
            delay: 0
          })
          animation.opacity(1).translateX(-100).step();
          that.animation = animation;
          that.setData({
            sBuy: 1,
            animation: that.animation.export()
          })
        }
      }
    })
  },

  /**
   * 关闭弹框
   */
  sBuyClose: function (event) {
    this.setData({
      sBuy: 0,
    })
  },

  /**
   * sku选中
   */
  skuSelect: function (event) {
    let that = this;
    let key = event.currentTarget.dataset.key;
    let k = event.currentTarget.dataset.k;
    let goods_info = that.data.goods_info;
    let arr = that.data.spec_list;
    let stock = that.data.stock;
    let sku_id = that.data.sku_id;
    let attr_value_items_format = that.data.attr_value_items_format;
    let promote_price = that.data.promote_price;
    let attr_value_items = {};
    let sku_info = that.data.sku_info;

    for (let i = 0; i < arr[key].value.length; i++) {
      arr[key].value[i].status = 0;
    }
    arr[key].value[k].status = 1;
    //拼合规格组
    for (let i = 0; i < arr.length; i++) {
      for (let l = 0; l < arr[i].value.length; l++) {
        if (arr[i].value[l]['status'] == 1) {
          attr_value_items[i] = arr[i].value[l].spec_id + ':' + arr[i].value[l].spec_value_id;
          attr_value_items.length = i + 1;
        }
      }
    }
    //规格组、库存判断
    for (let i = 0; i < goods_info.sku_list.length; i++) {
      let count = 1;
      for (let l = 0; l < attr_value_items.length; l++) {
        if (goods_info.sku_list[i].attr_value_items.indexOf(attr_value_items[l]) == -1) {
          count = 0;
        }
      }
      if (count == 1) {
        sku_id = goods_info.sku_list[i].sku_id;
        attr_value_items_format = goods_info.sku_list[i].attr_value_items_format;
        promote_price = goods_info.sku_list[i].promote_price;
        stock = goods_info.sku_list[i].stock;
        sku_info = goods_info.sku_list[i];
      }
    }
    that.setData({
      spec_list: arr,
      sku_id: sku_id,
      attr_value_items_format: attr_value_items_format,
      promote_price: promote_price,
      stock: stock
    })
  },

  /**
   * 商品数量调节
   */
  goodsNumAdjust: function (event) {
    let type = event.currentTarget.dataset.type;
    let num = this.data.goodsNum;
    let numCount = this.data.stock;

    if (type == 'add' && numCount > 0) {
      num++;
      if (num > numCount) {
        num = numCount;
      }
    } else if (type == 'minus' && numCount > 0) {
      num--;
      if (num <= 0) {
        num = 1;
      }
    } else {
      num = 1;
    }
    this.setData({
      goodsNum: num
    })
  },

  /**
   * 数量调节检测
   */
  goodsNumAdjustCheck: function (event) {
    let val = event.detail.value;
    let numCount = this.data.stock;
    if (val > numCount) {
      return numCount;
    } else if (val < 0) {
      return 0;
    }
  },

  /**
   * 加入购物车
   */
  addCart: function (event) {
    let that = this;

    let cart_detail = {
      shop_id: 0,
      shop_name: 'Niushop开源商城',
      trueId: that.data.goods_info.goods_id,
      goods_name: that.data.goods_info.goods_name,
      count: that.data.goodsNum,
      select_skuid: that.data.sku_id,
      select_skuName: that.data.sku_info.sku_name,
      price: that.data.promote_price,
      cost_price: that.data.sku_info.cost_price,
      picture: that.data.goods_info.picture
    };
    cart_detail = JSON.stringify(cart_detail);

    app.sendRequest({
      url: 'api.php?s=goods/addCart',
      data: {
        cart_detail: cart_detail,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: "POST",
      success: function (res) {
        let code = res.data.code;
        if (code > 0) {
          app.showBox(that, '加入购物车成功')
          that.setData({
            sBuy: 0
          })
        } else {
          app.showBox(that, '加入购物车失败')
        }
      }
    });
  },

  /**
   * 空库存
   */
  nullStock: function () {
    let that = this;
    app.showBox(that, '商品已售馨');
  }
})